package jcu.salt.client;

import jcu.salt.Logger;
import jcu.salt.io.Receiver;
import jcu.salt.io.Transmittable;

/**
 * Realizes the connection between a receiver for the data turbine
 * and a srb.  
 * 
 * @author SAL-T Team
 *
 */
public class TurbineReceiverThread extends Thread implements DataHandler {
	
	private Receiver rec;
	private SRBClient srb;
	private boolean active;

	/**
	 * set up the receiver thread using a certain {@link Receiver} as source 
	 * and a implementation of {@link SRBClient} as sink. 
	 * @param receiver
	 * @param srb
	 */
	public TurbineReceiverThread(Receiver receiver, SRBClient srb) {
		this.rec = receiver;
		this.srb = srb;
	}

	/**
	 * main loop runs as long as set active to try to receive from turbine
	 * using the {@link Receiver} 
	 */
	@Override
	public void run() {
		setActive(true);				

		rec.connect();
		while (isActive()) {
			try {
				Logger.log("Receive the data from data turbine");
				rec.receive(this);

			} catch (NullPointerException e) {
				System.out.println("\nProcess failed.\n");
				e.printStackTrace();
			}
		}
		rec.disconnect();
		
		super.run();
	}

	/**
	 * activates or deactivates the thread
	 * @param active
	 */
	public synchronized void setActive(boolean active) {
		if(isActive() && active == false) {
			rec.setActive(active);
		}
		this.active = active;		
	}

	/**
	 * check if thread is active
	 * @return true if active
	 */
	private synchronized boolean isActive() {
		return active;
	}

	/**
	 * get channel information used for receiving data from turbine
	 * @return channelname
	 */
	public String getChannel() {
		return rec.getChannel();
	}

	/**
	 * implements the handler routine used by the {@link Receiver} in
	 * order to delegate what to do with certain {@link Transmittable}.
	 */
	@Override
	public synchronized void  handleData(Transmittable received) {		
		if(received != null) {
			// Parse received data to console
			System.out.println("Received : " + received);
			System.out.println("bytes = [" + received.getData().length
					+ "]");
			System.out.println("Starting SRB store process");

			Logger.log("Write data to SRB");
			srb.writeData(received);
			System.out.println("Data successfully stored to SRB.");
			
		}
	}
}
